var delimiter = '-';
$(document).ready(function() {
    showMoreInfo($("#div_"), "imgInfo");
    showMoreInfo($("#div_zip"), "imgInfoZip");
    showMoreInfo($("#div_zip"), "imgInfoZip");
    showMoreInfo($("#div_corp"), "imgInfoCorp");
});

//window.onload=initForm;

//function initForm(){
   //$(".numeric").numeric(false);
//}
var clasesMarcadas = new Array();
clasesMarcadas[0] = '.obligatorio';
clasesMarcadas[1] = '.address';
clasesMarcadas[2] = '.citiesClass';
clasesMarcadas[3] = '.phone';

function initCamposObligatorios(){
    var i;
    for(i=0; i < clasesMarcadas.length; i++){
        $(clasesMarcadas[i]).each(
            function(index,value){
                $(value).after('<label style="color: red; display:none;">*</label>');
            }
        );
    }

}

function validate(){
    var isValid = true;
    var i;
    for(i=0; i < clasesMarcadas.length; i++){
        $(clasesMarcadas[i]).each(
            function(index,value){
                if($(value).val()==""){
                    $(value).next().show();
                    isValid=false;
                }else{
                    $(value).next().hide();
                }
            }
        );
    }

    if(isValid){
        beforeSaveCenter();
    }
    return isValid;

    /*
     $.validator.addMethod("valueNotEquals", function(value, element, arg){
     return value != arg;
     });

     $("#formEdit")
        .validate(
        {
            rules : {
                'institucion' : "required",
                'corporateName' : "required",
                'countries.country' : "required",
                'regions.region' : "required"
            }
        });


   if($("#formEdit").valid()){
       beforeSaveCenter();
       return true;
   }
   else
    return false;
    */
    beforeSaveCenter();
}

function validateClassWithName(className, isSave){
    var ok = true;
    $('.' + className).each(function(index,value){
        if(errorLabelWithName(value,value.parentNode.parentNode, isSave) == false)
        ok = false;
    });
    return ok;
}

function errorLabelWithName(select, fila, isSave){
    var idCell = select.name + "error";
    return errorLabel(select, fila, isSave,idCell);
}

function errorLabel(select, fila, isSave,idCell){
    var labelCell = document.getElementById(idCell);
    if(select.value == "-1" || select.value == ""){
            if(labelCell == null){
                var label = document.createElement('label');
                label.innerHTML = "This field is required";
                label.id = idCell;
                var cell = fila.insertCell(2);
                cell.appendChild(label);
            }
        if(isSave)
            return false;
        else
            return true;
    }
    else{
        if(labelCell != null){
            labelCell.parentNode.parentNode.removeChild(labelCell.parentNode);
        }
        return true;
    }
}

$(document).ready(function() {
    if(document.getElementById("regions") != null && document.getElementById("regions").value != ''){
        document.getElementById("regions").onchange();
    }
    populateAddresses();
    $('#trick :eq(0)').empty().append('<td><label>City</label></td><td width="218px"><select><option value=""  >Choose Country and Region</option></select></td>');
    areasTemp = $('#trick')[0].children[0];
    $(".citiesClass").each(function(i){
        this.id = "cities" + i;
        this.name= "c" + i;
    });
    $(".otherCityClass").each(function(i){
        this.id = "otherCity" + i;
        this.name = "oc" + i;
    });
    loadAddresses();
});

function getRegionsCenter(countryId, url){
    $("#regions").parent().parent().remove();
    $(".citiesdiv").empty().append('<td><label>City</label></td><td><select style="width:215px" name="c0" class="citiesClass"><option value=""  >Choose Country and Region</option></select><label style="color: red; display:none;">*</label></td>');
    $(".citiesClass").each(function(i){
        this.id = "cities" + i;
        this.name = "c" + i;
    });
    $(".otherCityClass").each(function(i){
        this.id = "otherCity" + i;
        this.name = "oc" + i;
    });
    $('option',$(".addresses")).remove();
    $(".addresses").append('<option value="-1" >Insert at least one address first</option>');    if(countryId != '' && countryId >= 0){
        $.ajax({
            traditional: true,
            type: "POST",
            url: url,
            data: { "countryId": countryId},
            success: function(result)
            {
                $("#regions").parent().parent().remove();
                $("#country").parent().parent().after(result);
                quitarCss();
            }
        });
    }

    if( countryId == 10){
        $("#trgln").show();
    } else{
        $("#trgln").hide();
    }

}

function getCitiesCenter(regionId, url){
    $("#regions").after('<img id="ajax-loader" src="../../styles/ajax-loader.gif" border="0"/>');
    $(".citiesdiv").empty().append('<td><label>City</label></td><td><select style="width:215px" name="c0" class="citiesClass"><option value="" >Choose Country and Region</option></select><label style="color: red; display:none;">*</label></td>');
    $(".citiesClass").each(function(i){
        this.id = "cities" + i;
        this.name = "c" + i;
    });
    $(".otherCityClass").each(function(i){
        this.id = "otherCity" + i;
        this.name = "oc" + i;
    });
    $('option',$(".addresses")).remove();
    $(".addresses").append('<option value="-1" >Insert at least one address first</option>');
    $("#ajax-loader").show();
    if(regionId != '' && regionId >= 0){
        $.ajax({
            traditional: true,
            type: "POST",
            dataType:"html",
            url: url,
            data: { "regionId": regionId},
            success: function(result)
            {
                $("#ajax-loader").remove();
                $(".citiesdiv").empty().append(result);
                $(".citiesClass").each(function(i){
                    this.id = "cities" + i;
                    this.name = "c" + i;
                });
                $(".otherCityClass").each(function(i){
                    this.id = "otherCity" + i;
                    this.name = "oc" + i;
                });
             //   $("#otherCity").parent().parent().hide();

                $('.citiesdiv select').each(function(index, value){
                    var total = $('.citiesdiv')[0].parentNode.children[0].children.length;

                    for (var i = 0; i < total; i++){
                        $(".citiesdiv")[index].parentNode.children[0].children[i].value = "";
                    }

                    var s = value;
                    var v = $('#addrCity' + index).val();

                    for ( var i = 0; i < s.options.length; i++ ) {
                        if ( s.options[i].text == v ) {
                            s.options[i].selected = true;
                            return;
                        }
                        else{
                            s.options[0].selected = true;
                        }
                    }
                });
                isOtherCity();
                loadAddresses();
            }
        });
    }
}

function isOtherCity(){

    $('.citiesdiv').each(function(index, value) {
        if(value.children[1].children[0].value == -2){
            $('.citiesdiv:eq('+index+')').children(':eq(2)').show();
            $('.citiesdiv:eq('+index+')')[0].children[1].onchange = function(){populateAddresses(); return false;};
        }else{
            $('.citiesdiv:eq('+index+')').children(':eq(2)').hide();
        }
    });
    populateAddresses();
}

function beforeSaveCenter(){
    $('.addrAddress').each(function(index,value){
        value.value = $("#table_address tr")[value.parentNode.parentNode.rowIndex + 1].children[1].children[0].value;
    });
    $('.citiesdiv').each(function(index,value){
        var filaHidden = $("#table_address tr")[value.rowIndex - 2];
        var celdaCity;
        var celdaRegion;
        var celdaCountry;
        if (filaHidden.children.length == 5){
            celdaCity = filaHidden.children[2].children[0];
            celdaRegion = filaHidden.children[3].children[0];
            celdaCountry = filaHidden.children[4].children[0];
        }
        else{
            celdaCity = filaHidden.children[1].children[0];
            celdaRegion = filaHidden.children[2].children[0];
            celdaCountry = filaHidden.children[3].children[0];
        }
        if(value.children[1].value == -2){
            celdaCity.value = value.children[2].children[0].value;
        }
        else{
            celdaCity.value = value.children[1].children[0].options[value.children[1].children[0].selectedIndex].text;
        }
        if($('#regions')[0] != null)
            celdaRegion.value = $('#regions')[0].options[$('#regions')[0].selectedIndex].text;
        celdaCountry.value = $('#country')[0].options[$('#country')[0].selectedIndex].text;
    });

    $('.addressesdiv').each(function(index, value){
        value.children[1].value = value.children[5].options[value.children[5].selectedIndex].text.split(', ')[0];
        value.children[2].value = value.children[5].options[value.children[5].selectedIndex].text.split(', ')[1];
        if($('#regions')[0] != null)
            value.children[3].value = $('#regions')[0].options[$('#regions')[0].selectedIndex].text;
        value.children[4].value = $('#country')[0].options[$('#country')[0].selectedIndex].text;
    });

}

function addRowAddress(tableID) {

    var isValid = true;
    var i;
    for(i=1; i < clasesMarcadas.length; i++){
        $(clasesMarcadas[i]).each(
            function(index,value){
                if($(value).val()==""){
                    $(value).next().show();
                    isValid=false;
                }else{
                    $(value).next().hide();
                }
            }
        );
    }

    if(isValid){

        var table = document.getElementById(tableID);

        var cant = document.getElementById("cantAddr");
        var newId = cant.value;
        var idAnt = parseInt(newId,10) - parseInt(1,10);
        var val = parseInt(cant.value,10) + parseInt(1,10);
        cant.value = val;

        for(var k = newId; k>0; k--){
            if (document.getElementById("delAddrCell" + k) != null)
                break;
        }

        var idAfter = '#delAddrCell' + k;

        var row6 = $('#delAddrCell' + k).parent().clone()[0];
        row6.cells[1].id="delAddrCell"+newId;
        row6.cssClass="trNuevoDocumento";
        $(idAfter).parent().after(row6);

        var row3 = $('#email' + k).parent().parent().clone()[0];
        row3.cells[1].children[0].id="email" + newId;
        row3.cells[1].children[0].name="addresses[" + newId + "].email";
        row3.cells[1].children[0].value="";
        $(idAfter).parent().after(row3);

        var row4 = $('#fax' + k).parent().parent().clone()[0];
        row4.cells[1].children[0].id="fax" + newId;
        row4.cells[1].children[0].name="addresses[" + newId + "].fax";
        row4.cells[1].children[0].value="";
        $(idAfter).parent().after(row4);

        var row5 = $('#phone' + k).parent().parent().clone()[0];
        row5.cells[1].children[0].id="phone" + newId;
        row5.cells[1].children[0].name="addresses[" + newId + "].phone";
        row5.cells[1].children[0].value="";
        $(idAfter).parent().after(row5);

        var row9 = $('#zipCode' + k).parent().parent().clone()[0];
        row9.cells[1].children[0].id="zipCode" + newId;
        row9.cells[1].children[0].name="addresses[" + newId + "].zipCode";
        row9.cells[1].children[0].value="";
        $(idAfter).parent().after(row9);

        var row2 = $('#cities' + k).parent().parent().clone()[0];
        row2.cells[1].children[0].value="-1";
        row2.cells[1].children[0].id="cities" + newId;
        row2.cells[1].children[0].name="c" + newId;
        if(row2.cells.length == 3){
            var idAntStr = "otherCity" + idAnt;
            if(row2.cells[2].children[0].id == idAntStr){
                row2.cells[2].children[0].id="otherCity" + newId;
                $('#otherCity' + newId).hide();
            }
            else{
                row2.cells[2].children[0].id="otherCity" + newId;
                row2.cells[2].children[0].name = "oc" + newId;
            }
        }
        if(row2.cells.length == 4){
            row2.cells[2].children[0].id="cities" + newId + "error";
            row2.cells[3].children[0].id="otherCity" + newId;
            row2.cells[3].children[0].name="oc" + newId;
            $('#otherCity' + newId).hide();
        }
        $(idAfter).parent().after(row2);

        var row1 = $('#addressField' + k).parent().parent().clone()[0];
        row1.cells[1].children[0].id="addressField" + newId;
        row1.cells[1].children[0].name="a" + newId;
        row1.cells[1].children[0].value="";
        if(row1.cells[1].children == 2){
            row1.cells[1].children[1].for = "addressField" + newId;
        }
        $(idAfter).parent().after(row1);

        var row0 = $('#addrAddress' + k).parent().parent().clone()[0];
        var i = 0;
        if(row0.children.length == 5){
            row0.children[0].children[0].name="addresses["+newId+"].id";
            row0.children[0].children[0].value="";
            i = 1;
        }
        row0.children[i].children[0].id="addrAddress" + newId;
        row0.children[i].children[0].name="addresses["+newId+"].address";
        row0.children[i].children[0].value="";
        i++;
        row0.children[i].children[0].name="addresses["+newId+"].city";
        row0.children[i].children[0].value="";
        row0.children[i].children[0].id="addrCity" + newId;
        i++
        row0.children[i].children[0].name="addresses["+newId+"].province";
        row0.children[i].children[0].value="";
        i++
        row0.children[i].children[0].name="addresses["+newId+"].country";
        row0.children[i].children[0].value="";
        $(idAfter).parent().after(row0);

        isOtherCity();
        showMoreInfo($("#div_"), "imgInfo");
    }
}

function addRowSpecialty(tableID) {
     var table = document.getElementById(tableID);

     var cant = document.getElementById("cantTherap");
     var newId = cant.value;
     var val = parseInt(cant.value,10) + parseInt(1,10);
     cant.value = val;

     for(var k = newId; k>0; k--){
        if (document.getElementById("delTherapCell" + k) != null)
        break;
     }

     var idAfter = '#delTherapCell' + k;

     var row5 = $('#delTherapCell' + k).parent().clone()[0];
     row5.cells[1].id="delTherapCell"+newId;
     row5.cssClass="trNuevoDocumento";
     $(idAfter).parent().after(row5);

     var row4 = $('#observation' + k).parent().parent().clone()[0];
     row4.cells[1].children[0].value="";
     row4.cells[1].children[0].name="centro.centroAddresses["+newId+"].observation";
     row4.cells[1].children[0].id="observation" + newId;
     $(idAfter).parent().after(row4);

    var row3 = $('#addresshidden' + k).parent().parent().clone()[0];
    if(row3.cells.length == 3){
        row3.cells[2].children[0].id="selectAddress" + newId + "error";
    }
    row3.cells[1].children[0].name="centro.centroAddresses["+newId+"].address.id";
    row3.cells[1].children[0].value="";
    row3.cells[1].children[1].name="centro.centroAddresses["+newId+"].address.address";
    row3.cells[1].children[1].id="addresshidden" + newId;
    row3.cells[1].children[1].value="";
    row3.cells[1].children[2].name="centro.centroAddresses["+newId+"].address.city";
    row3.cells[1].children[2].value="";
    row3.cells[1].children[3].name="centro.centroAddresses["+newId+"].address.province";
    row3.cells[1].children[3].value="";
    row3.cells[1].children[4].name="centro.centroAddresses["+newId+"].address.country";
    row3.cells[1].children[4].value="";
    row3.cells[1].children[5].id="selectAddress" + newId;
    row3.cells[1].children[5].value="";
    $(idAfter).parent().after(row3);

    var row2 = $('#copySelect' + k).parent().parent().clone()[0];
    if(row2.cells.length == 3){
        row2.cells[2].children[0].id="centro.centroAddresses["+newId+"].therapeuticArea.iderror";
    }
    row2.cells[1].children[0].value="-1";
    row2.cells[1].children[0].name="centro.centroAddresses["+newId+"].therapeuticArea.id";
    row2.cells[1].children[2].value="-1";
    row2.cells[1].children[2].name="centro.centroAddresses["+newId+"].speciality.id";
    if(row2.cells[1].children.length == 6){
        row2.cells[1].children[3].parentNode.removeChild(row2.cells[1].children[3]);
    }
    row2.cells[1].children[3].value="";
    row2.cells[1].children[3].id="specialityhidden";
    row2.cells[1].children[4].id="copySelect"+ newId;
    $(idAfter).parent().after(row2);

    populateAddresses();

}

function calcularCantTherap(){
    var cantTher = document.getElementById("cantTherap");
    if(cantTher.value == 0){
        var cant = 0;

        $('.addressesdiv').each(function(index, value){
            cant++;
        });
        cantTher.value = cant;
    }
}

function deleteRowAddress(tableID, fila){
    var table = document.getElementById(tableID);
    var cant = document.getElementById("cantAddr");

    var rows = table.getElementsByTagName('tr');
    var size = rows.length;
    for(var j = 0; j < rows.length; j++ ){
        if(rows[j].id == fila[0].id && rows[j].cells[1].id == fila[0].cells[1].id){
            break;
        }
    }

    if(cant.value == 1){
        var borrados = 0;
        var x = j - 1;
        while(borrados < 7){
            if(rows[x].cells[1] != null){
                rows[x].cells[1].children[0].value="";
                if(rows[x].cells.length > 2){
                    for(var len = 0; len< rows[x].cells.length; len++)
                        rows[x].cells[len].children[0].value="";
                }
                borrados++;
            }
            x--;
        }
        return;
    }
    else{

        var borrados = 0;
        var x = j;
        while(borrados < 8){
            rows[x].parentNode.removeChild(rows[x]);
            if(rows[x].cells[1] != null){
                borrados++;
            }
            x--;
        }

        var val = parseInt(cant.value,10) - parseInt(1,10);
        cant.value = val;
    }

    numerarDirecciones();
    populateAddresses();
}

function numerarDirecciones(){
    $(".addrId").each(function(i){
        this.name = "addresses["+i+"].id";
    });
    $(".addrAddress").each(function(i){
        this.id = "addrAddress" + i;
        this.name = "addresses["+i+"].address";
    });
    $(".addrCity").each(function(i){
        this.name = "addresses["+i+"].city";
    });
    $(".addrProvince").each(function(i){
        this.name = "addresses["+i+"].province";
    });
    $(".addrCountry").each(function(i){
        this.name = "addresses["+i+"].country";
    });
    $(".address").each(function(i){
        this.id = "addressField" + i;
        this.name = "a" + i;
    });
    $(".citiesClass").each(function(i){
        this.id = "cities" + i;
        this.name = "c" + i;
    });
    $(".otherCityClass").each(function(i){
        this.id = "otherCity" + i;
        this.name = "oc" + i;
    });
    $(".delAddress").each(function(i){
        this.id = "delAddrCell" + i;
    });
    $(".phone").each(function(i){
        this.id = "phone" + i;
        this.name = "addresses["+i+"].phone";
    });
    $(".email").each(function(i){
        this.id = "email" + i;
        this.name = "addresses["+i+"].email";
    });
    $(".fax").each(function(i){
        this.id = "fax" + i;
        this.name = "addresses["+i+"].fax";
    });
    $(".zipCode").each(function(i){
        this.id = "zipCode" + i;
        this.name = "addresses["+i+"].zipCode";
    });
}

function deleteRowSpecialty(tableID, fila) {
    var table = document.getElementById(tableID);
    var cant = document.getElementById("cantTherap");

    var rows = table.getElementsByTagName('tr');
    var size = rows.length;
    for(var j = 0; j < rows.length; j++ ){
        if(rows[j].id == fila[0].id && rows[j].cells[1].id == fila[0].cells[1].id){
            break;
        }
    }

    if(cant.value == 1){
        var borrados = 0;
        var x = j - 1;
        while(borrados < 3){
            if(rows[x].cells[1] != null){
                rows[x].cells[1].children[0].value="";
                if(rows[x].cells.length > 2){
                    for(var len = 0; len< rows[x].cells.length; len++)
                        rows[x].cells[len].children[0].value="";
                }
                borrados++;
            }
            x--;
        }
        return;
    }
    else{

        var borrados = 0;
        var x = j;
        while(borrados < 4){
            rows[x].parentNode.removeChild(rows[x]);
            if(rows[x].cells[1] != null){
                borrados++;
            }
            x--;
        }

        var val = parseInt(cant.value,10) - parseInt(1,10);
        cant.value = val;
    }

    numerarTherap();

}

function numerarTherap(){
    $(".areass").each(function(i){
        this.name = "centro.centroAddresses["+i+"].therapeuticArea.id";
    });
    $("#specialities").each(function(i){
        this.name="centro.centroAddresses["+i+"].speciality.id";
    });
    $(".copyClass").each(function(i){
        this.id="copySelect" + i;
    });
    $(".tAddrId").each(function(i){
        this.name="centro.centroAddresses["+i+"].address.id";
    });
    $(".tAddrAddress").each(function(i){
        this.name="centro.centroAddresses["+i+"].address.address";
        this.id="addresshidden" +i;
    });
    $(".tAddrCity").each(function(i){
        this.name="centro.centroAddresses["+i+"].address.city";
    });
    $(".tAddrProvince").each(function(i){
        this.name="centro.centroAddresses["+i+"].address.province";
    });
    $(".tAddrCountry").each(function(i){
        this.name="centro.centroAddresses["+i+"].address.country";
    });
    $(".tCentroAddrId").each(function(i){
        this.name="centro.centroAddresses["+i+"].id";
    });
    $(".tCentroId").each(function(i){
        this.name="centro.centroAddresses["+i+"].centro.id";
    });
    $(".addresses").each(function(i){
        this.id="selectAddress" +i;
    });
    $(".obsClass").each(function(i){
        this.id="observation" + i;
        this.name="centro.centroAddresses["+i+"].observation";
    });
    $(".delTherap").each(function(i){
        this.id = "delTherapCell" + i;
    });
}

function checkArea(value, selectedIndex, area){
    areasRedirectPropio(selectedIndex, area);
    if(value == -1){
        area.style.display = "none";
    }else{
        area.style.display = "";
    }
}

function populateAddresses(){
    $('#trick :eq(0)').empty().append('<td><label>City</label></td><td><select><option value="-1">Choose Country and Region</option></select></td>');
    areasTemp = $('#trick')[0].children[0];

    if($('.citiesdiv')[0].children.length == 2){
        $('option',$(".addresses")).remove();
        $(".addresses").append('<option value="-1" >Insert at least one address first</option>');
        return;
    }
    $('.addresses').each(function(index, value){
        var select = value;
        var selected = value.value;

        if(select.prop) {
            var options = select.prop('options');
        }
        else {
            var options = select.options;
        }
        var cantAddr = 0;
        $(".address").each(function(index,value) {
            if(value.value.trim().length > 0 && $('.citiesdiv')[index].cells[1].children[0].value != '' && $('.citiesdiv')[index].cells[1].children[0].value != -1){
                cantAddr++;
                if(cantAddr == 1){
                    $('option', select).remove();
                    options[options.length] = new Option("Choose an Address", -1);
                }

                var city = $('.citiesdiv')[index].cells[1].children[0].options[$('.citiesdiv')[index].cells[1].children[0].selectedIndex].text;
                if($('.citiesdiv')[index].cells[1].children[0].value == -2){
                    city = $('.citiesdiv')[index].children[2].children[0].value;
                }
                options[options.length] = new Option(value.value.trim() + delimiter + city, value.value.trim());
            }
        });
        for ( var i = 0; i < value.options.length; i++ ) {
            if ( value.options[i].value == selected ) {
                value.options[i].selected = true;
                return;
            }
            else{
                value.options[0].selected = true;
            }
        }
    });

    $('#trick :eq(0)').empty().append('<td><label>City</label></td><td><select><option value="-1"  >Choose Country and Region</option></select></td>');
    areasTemp = $('#trick')[0].children[0];

    $(".citiesClass").each(function(i){
        this.id = "cities" + i;
        this.name = "c"+ i;
    });
    $(".otherCityClass").each(function(i){
        this.id = "otherCity" + i;
        this.name = "oc" + i;
    });
}

function loadAddresses() {
    $('.addressesdiv').each(function(index, div){
        var s =  div.children[5];
        var v = div.children[1].value;
        for ( var i = 0; i < s.options.length; i++ ) {
            if ( s.options[i].value == v ) {
                s.options[i].selected = true;
                return;
            }
            else{
                s.options[0].selected = true;
            }
        }
    });
    $('.areass').each(function(index,value){
        checkArea(value.value, value.selectedIndex, value.parentNode.children[2]);
        value.parentNode.children[2].value = value.parentNode.children[4].value;
    });
    calcularCantTherap();
}

function areasRedirectPropio(x, areas) {
    var areasTemp2 = areas;
    var selected = false;
    for (m = areasTemp2.options.length - 1; m >= 0; m--) {
        areasTemp2.remove(m);
    }

    for (i = 0; i < areasGroup[x].length; i++) {
        areasTemp2.options[i] = new Option(areasGroup[x][i].text, areasGroup[x][i].value);
    }

    if ((areasTemp2.options.length > 0) && (! selected)) {
        areasTemp2.options[0].selected = true;
    }
}
